<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

// 定义emit事件
const emit = defineEmits(['openRegister'])

// 使用store和router
const userStore = useUserStore()
const router = useRouter()

// 控制对话框显示
const dialogVisible = ref(false)

// 表单数据
const loginForm = reactive({
  email: '',
  password: ''
})

// 表单验证规则
const rules = {
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input the password', trigger: 'blur' },
    { min: 6, max: 20, message: 'Password length is between 6 and 20 characters', trigger: 'blur' }
  ]
}

// 表单引用
const loginFormRef = ref()

// 登录加载状态
const loading = ref(false)

// 打开登录对话框
const openLoginDialog = () => {
  dialogVisible.value = true
}

// 关闭登录对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
  loginForm.email = ''
  loginForm.password = ''
}

// 登录提交
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (valid) {
      loading.value = true

      // 调用userStore的登录方法
      const response = await userStore.login({
        email: loginForm.email,
        password: loginForm.password
      })
      // 登录成功
      if (response && response.status === 'success') {
        closeDialog()
        await userStore.fetchUnreadMessageCount()
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  closeDialog()
  // 触发父组件打开注册对话框
  emit('openRegister')
}

// 暴露方法给父组件调用
defineExpose({
  openLoginDialog
})
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      width="420px"
      :before-close="closeDialog"
      :show-close="false"
      class="login-dialog"
      center
  >
    <template #header>
      <div class="login-header">
        <span>User Login</span>
      </div>
    </template>
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
    >
      <el-form-item prop="email">
        <el-input
            v-model="loginForm.email"
            placeholder="Please input email"
            :maxlength="150"
            clearable
            size="large"
            :prefix-icon="Message"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="Please input password"
            show-password
            :maxlength="150"
            clearable
            size="large"
            :prefix-icon="Lock"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div class="register-link">
          <span>No account?</span>
          <el-button type="text" @click="goToRegister">Register Now</el-button>
        </div>
        <div class="button-group">
          <el-button @click="closeDialog">Cancel</el-button>
          <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
          >Login</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.login-header {
  font-size: 24px;
}

.login-form {
  .el-form-item {
    margin-bottom: 24px;
  }
}

.dialog-footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 16px;

  .register-link {
    text-align: left;
    color: #666;
    font-size: 14px;

    span {
      margin-right: 4px;
    }

    .el-button {
      padding: 0;
      font-size: 14px;
      color: #409EFF;

      &:hover {
        color: #66b1ff;
      }
    }
  }

  .button-group {
    text-align: right;

    .el-button {
      margin-left: 10px;
    }
  }
}

</style>